<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="组织名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入组织名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['biz:emgResource:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="emgResourceTableRef"
        v-loading="loading"
        :data="emgResourceList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="组织名称" prop="name" />
        <el-table-column label="资源点" align="center" prop="isResource">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isResource" />
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="contact" />
        <el-table-column label="联系方式" align="center" prop="phone" />
        <el-table-column label="地址" align="center" prop="address" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['biz:emgResource:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['biz:emgResource:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['biz:emgResource:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改应急资源组织对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" :width="form.isResource === 'Y' && form.id ? '1400px' : '500px'" append-to-body>
      <el-form ref="emgResourceFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="form.isResource === 'Y' && form.id ? 8 : 24" class="p-2">
            <el-form-item label="父编号" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="emgResourceOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="请选择父编号"
                @node-click="handleClick"
                check-strictly
              />
            </el-form-item>
            <el-form-item label="组织名称" prop="name">
              <el-select v-if="isCompany" v-model="form.name">
                <el-option v-for="item in companyOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-input v-else v-model="form.name" placeholder="请输入组织名称" />
            </el-form-item>
            <el-form-item label="是否资源点" prop="isResource">
              <el-switch v-model="form.isResource" @change="editChange" active-value="Y" inactive-value="N" />
            </el-form-item>
            <div v-if="form.isResource === 'Y'">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="form.contact" placeholder="请输入联系人" />
              </el-form-item>
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系方式" />
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入地址" />
              </el-form-item>
              <map-container ref="mapRef" containerStyle="width: 100%; height: 200px" @updateCoordinates="handleCoordinatesUpdate" @load="mapLoad" />
              <el-form-item label="经度" prop="lon">
                <el-input v-model="form.lon" placeholder="请输入经度" />
              </el-form-item>
              <el-form-item label="纬度" prop="lat">
                <el-input v-model="form.lat" placeholder="请输入纬度" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="16" v-if="form.isResource === 'Y' && form.id">
            <resource-detail :emg-resource-id="form.id" />
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EmgResource" lang="ts">
import { listEmgResource, getEmgResource, delEmgResource, addEmgResource, updateEmgResource } from '@/api/biz/emgResource';
import { EmgResourceVO, EmgResourceQuery, EmgResourceForm } from '@/api/biz/emgResource/types';
import MapContainer from '@/views/biz/components/mapContainer/index.vue';
import ResourceDetail from '@/views/biz/emgResource/resourceDetail.vue';
import { EmgCompanyVO } from '@/api/biz/emgCompany/types';
import { listEmgCompany } from '@/api/biz/emgCompany';

type EmgResourceOption = {
  id: number;
  name: string;
  children?: EmgResourceOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));

const emgResourceList = ref<EmgResourceVO[]>([]);
const emgResourceOptions = ref<EmgResourceOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);
const mapRef = ref(null);
const isCompany = ref(false);
const companyOptions = ref<EmgCompanyVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const emgResourceFormRef = ref<ElFormInstance>();
const emgResourceTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EmgResourceForm = {
  id: undefined,
  name: undefined,
  parentId: undefined,
  isResource: undefined,
  contact: undefined,
  phone: undefined,
  address: undefined,
  lon: undefined,
  lat: undefined
};

const data = reactive<PageData<EmgResourceForm, EmgResourceQuery>>({
  form: { ...initFormData },
  queryParams: {
    name: undefined,
    parentId: undefined,
    isResource: undefined,
    contact: undefined,
    phone: undefined,
    address: undefined,
    lon: undefined,
    lat: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '组织名称不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父编号不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询应急资源组织列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEmgResource(queryParams.value);
  const data = proxy?.handleTree<EmgResourceVO>(res.data, 'id', 'parentId');
  if (data) {
    emgResourceList.value = data;
    loading.value = false;
  }
};

/** 查询应急资源组织下拉树结构 */
const getTreeselect = async () => {
  const res = await listEmgResource();
  emgResourceOptions.value = [];
  const data: EmgResourceOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<EmgResourceOption>(res.data, 'id', 'parentId');
  emgResourceOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  emgResourceFormRef.value?.resetFields();
  if (mapRef.value) {
    mapRef.value.clearPoint();
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: EmgResourceVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加应急资源组织';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(emgResourceList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: EmgResourceVO[], status: boolean) => {
  data.forEach((item) => {
    emgResourceTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: EmgResourceVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getEmgResource(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改应急资源组织';
};

/** 提交按钮 */
const submitForm = () => {
  emgResourceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateEmgResource(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addEmgResource(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: EmgResourceVO) => {
  await proxy?.$modal.confirm('是否确认删除应急资源组织编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delEmgResource(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const editChange = (e) => {
  if (e === 'N') {
    form.value.contact = null;
    form.value.phone = null;
    form.value.lon = null;
    form.value.lat = null;
    form.value.address = null;
  }
};

const handleClick = (node) => {
  isCompany.value = node.name === '企业';
};

/** 处理地图坐标更新 */
const handleCoordinatesUpdate = (coordinates) => {
  form.value.lon = coordinates.longitude;
  form.value.lat = coordinates.latitude;
};

const mapLoad = () => {
  mapRef.value.enableDrawPoint();
  if (form.value.lat && form.value.lon) {
    mapRef.value.setPoint(form.value.lon, form.value.lat);
  }
};

onMounted(() => {
  getList();
  listEmgCompany({ isSupply: 'Y' }).then((res) => {
    companyOptions.value = res.rows;
  });
});
</script>
